package com.chenxi.vhr.rabbitmq;

import com.chenxi.vhr.bean.message.MqMessage;
import com.chenxi.vhr.bean.vo.EmployeeVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 消息接收者
 * @author : zhangchenxi
 * @create : 2022-02-13
 **/
@Component
public class MessageReceiver {
    public static final Logger logger = LoggerFactory.getLogger(MessageReceiver.class);

    @Autowired
    JavaMailSender javaMailSender;

    @Autowired
    TemplateEngine templateEngine;

    @Autowired
    MailProperties mailProperties;

    // 监听邮件发送的消息
    @RabbitListener(queues = "Mail-Queue")
    public void receiverMsgAdnSendMail(MqMessage message) {
        EmployeeVo emp = (EmployeeVo) message.getData();
        // 封装消息
        Map<String, Object> map = new HashMap<>();
        map.put("name", emp.getName());
        map.put("workNo", emp.getWorkNo());
        map.put("positionName", emp.getPositionName());
        map.put("jobLevelName", emp.getJobName());
        map.put("deptName", emp.getDeptName());
        map.put("salary", 12500);

        // 收到消息发送邮件
        MimeMessage mailMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mailMessage);
        // 发送人
        try {
            helper.setFrom(mailProperties.getUsername());
            // 收件人
            helper.setTo(emp.getEmail().trim());
            // 抄送(明着)
            helper.setCc("15950532022@163.com");
            helper.setSentDate(new Date());
            helper.setSubject("欢迎入职新公司！！！");

            Context ctx = new Context();
            ctx.setVariables(map);
            String content = templateEngine.process("mail.html", ctx);
            helper.setText(content, true);
            // 邮件发送
            javaMailSender.send(mailMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
            logger.error("邮件发送失败！！" + e.getMessage());
        }
    }

}
